package com.baidu.ota.impl;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.baidu.commonlib.interfaces.IUpgradeInterface;
import com.baidu.ota.application.BaseApplication;
import com.baidu.ota.interfaces.ISystemInfo;
import com.baidu.ota.utils.DeviceUtil;
import com.baidu.ota.utils.MetaData;
import com.baidu.ota.utils.RecoveryUtil;
import com.baidu.ota.utils.SystemPropUtil;
import com.baidu.otasdk.ota.Constants;
import com.baidu.otasdk.ota.DefaultUpgradeImpl;

import java.io.File;

/**
 * LaunchApplication的代理实现类，类名必须为ApplicationImpl
 */
public class ApplicationImpl extends ApplicationProxyBase {

    private final Application host;

    public ApplicationImpl(Application app) {
        host = app;
    }

    /**
     * 系统信息
     *
     * @return object
     */
    @Override
    public ISystemInfo getSystemInfo() {
        return new MySystemInfo();
    }

    /**
     * 自定义升级对象
     *
     * @param context cx
     * @param pid     产品线id
     * @return 返回null则使用SDK内部默认的Recovery升级实现
     */
    @Override
    public IUpgradeInterface getCustomUpgrade(Context context, String pid) {
        // todo 根据产品ota实际情况，是否需要自定义实现升级逻辑
        return new MyUpgradeImpl(context, pid);
    }

    /**
     * 系统升级包的下载/升级路径（前提：此路径在recovery模式下已挂载）
     *
     * @param context cx
     * @return 返回""则使用SDK内部默认的Environment.getDownloadCacheDirectory().getAbsolutePath();
     */
    @Override
    public String getUpgradePath(Context context) {
        // todo 根据系统升级实际情况，返回ota包下载的路径
        return Environment.getDownloadCacheDirectory().getAbsolutePath();
    }

    private class MySystemInfo implements ISystemInfo {
        /**
         * todo 返回系统版本号
         * 版本号规则：4段式：x.x.x.x，x为整数，范围不能超过long
         *
         * @return string
         */
        @Override
        public String getVersion() {
            String field = MetaData.getString(MetaData.OTA_VERSION_FIELD);
            String ver = SystemPropUtil.get(field, "0.0.0.0");
            Log.w(Constants.TAG, "version_field=" + field + ",version=" + ver);
            return ver;
        }

        /**
         * todo 返回设备实际的model
         *
         * @return string
         */
        @Override
        public String getModel() {
            return Build.MODEL;
        }

        /**
         * todo 返回设备实际的cpu
         *
         * @return string
         */
        @Override
        public String getCPU() {
            return Build.CPU_ABI;
        }

        /**
         * todo 返回设备id（标识这台设备的唯一编码，恒定不变且不与其他设备重复）
         * 根据实际设备环境，从系统信息中获取，比如设备序列号、芯片序列号、mac地址、IMEI等等
         *
         * @return string
         */
        @SuppressLint("MissingPermission")
        @Override
        public String getDeviceId() {
            String field = MetaData.getString(MetaData.DEVICE_ID_FIELD);

            String id;
            if (TextUtils.isEmpty(field) || "SN".equals(field)) {
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    id = Build.getSerial();
                } else {
                    id = Build.SERIAL;
                }
            } else if ("IMEI".equals(field)) {
                id = DeviceUtil.getIMei(host);
            } else if ("MAC".equals(field)) {
                id = DeviceUtil.getMac(host);
            } else {
                id = SystemPropUtil.get("ro.serialno", Build.UNKNOWN);
            }
            // String id = SystemPropUtil.get("ro.serialno", Build.UNKNOWN);
            Log.w(Constants.TAG, "device_id_field=" + field + ",device_id=" + id);
            return id;
        }

        @Override
        public String getChannel() {
            String field = MetaData.getString(MetaData.CHANNEL_FIELD);
            String channel = "";
            if (!TextUtils.isEmpty(field)) {
                SystemPropUtil.get(field, "");
            }
            Log.w(Constants.TAG, "channel_field=" + field + ",channel=" + channel);
            return channel;
        }

        /**
         * 获取字段值
         *
         * @param key key(0:产品线id,1:产品线密钥)
         * @return string
         */
        @Override
        public String getFieldValue(int key) {
            String field = "";
            if (key == 0) {
                field = MetaData.getString(MetaData.PRODUCT_ID_FIELD);
            } else if (key == 1) {
                field = MetaData.getString(MetaData.PRODUCT_KEY_FIELD);
            }
            if (!TextUtils.isEmpty(field)) {
                String val = SystemPropUtil.get(field, "");
                Log.w(Constants.TAG, "field=" + field + ",value=" + val);
                return val;
            }
            return "";
        }
    }

    private static class MyUpgradeImpl extends DefaultUpgradeImpl {
        MyUpgradeImpl(Context cx, String pid) {
            super(cx, pid);
        }

        @Override
        public String installSystem(String pkg, File file, boolean silence) {
//            for (int i = 5; i < 100; i += 5) {
//                try {
//                    Thread.sleep(10);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                getListener(pkg).onProgress(pkg, Constants.STAGE_INSTALL_PACKAGE, i);
//            }
//            getListener(pkg).onWriteDone(pkg);
//
//            if (!BaseApplication.nextRebootUpgrade) {
//                return super.installSystem(pkg, file, silence);
//            }
            String res = Constants.UPGRADE_PENDING;
            try {
                RecoveryUtil.installNow(context, file);
            } catch (Exception e) {
                res = e.toString();
                e.printStackTrace();
            }
            return res;
        }
    }
}